<!-- 物资类型-物资类型种类页面弹窗页面 -->
<template>
  <px-dialog
    v-if="addDialogVisible"
    v-model="addDialogVisible"
    class="equip-dialog"
    title="添加物资"
    width="960px"
    @open="openDialog"
    @close="closeDialog"
  >
    <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
      <px-row>
        <px-col :span="12">
          <px-form-item label="物资类型">
            <px-tree-select
              v-model="formValue.typeName"
              filterable
              clearable
              placeholder="请选择物资类型"
              :props="{
                children: 'children',
                label: 'name',
                value: 'code'
              }"
              :data="typeCodeList"
              :render-after-expand="false"
              check-strictly
              @focus="queryTypeCodeList"
              @node-click="nodeClick"
              @change="clearQT"
            />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="物资名称" prop="name">
            <px-select
              v-model="formValue.name"
              :disabled="!formValue.typeName"
              maxlength="50"
              filterable
              clearable
              remote
              allow-create
              value-key="id"
              placeholder="请先选择物资种类"
              :loading="searchLoading"
              :remote-method="attachRemoteMethod"
              @change="deviceNameAttachChange"
            >
              <px-option v-for="item in deviceAttachOptions" :key="item.id" :label="item.name" :value="item.name" />
            </px-select>
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="品牌" prop="brand">
            <px-input v-model="formValue.brand" placeholder="请输入" maxlength="50" clearable />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="规格型号" prop="specification">
            <px-input v-model="formValue.specification" placeholder="请输入" maxlength="50" clearable />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="单位" prop="unit">
            <px-input v-model="formValue.unit" placeholder="请输入" maxlength="50" clearable />
          </px-form-item>
        </px-col>
        <px-col :span="12">
          <px-form-item label="安全库存">
            <px-input-number v-model="formValue.safeStock" placeholder="请输入" :min="0" maxlength="50" />
            <px-tooltip content="小于等于安全库存会给预警提醒人发送邮件提醒" placement="top">
              <span style="margin-top: 8px; margin-left: 4px">
                <px-icon :size="18">
                  <InfoCircleFilled />
                </px-icon>
              </span>
            </px-tooltip>
          </px-form-item>
        </px-col>
      </px-row>
      <px-col :span="24">
        <px-form-item label="备注" prop="remark">
          <px-input
            v-model="formValue.remark"
            type="textarea"
            placeholder="请输入问题描述"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="1000"
            clearable
            show-word-limit
          />
        </px-form-item>
      </px-col>
    </px-form>
    <div class="equip-dialog-footer">
      <px-button @click="closeDialog">取消</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </px-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, toRefs } from "vue";
import { PxMessage } from "px-ui";
import { queryDictData } from "@/api/common";
import { addToolMaterial, editToolMaterial, searchTreeMaterial, queryMaterialTableList } from "@/api/erc/material";

// 调用父级-关闭弹窗、查询列表方法
const emits = defineEmits(["closeDialog", "AddTableRow"]);
// 父级传过来的值
const props = defineProps(["addDialogVisible"]);

const addDialogVisible = computed(() => props.addDialogVisible);
// 页面本身的值
const formRef = ref();
const searchLoading = ref(false);
const deviceAttachOptions = ref<Array<any>>([]);
const state = reactive<any>({
  typeTitle: "新增物资种类",
  formValue: {
    typeName: "",
    typeCode: "",
    name: "",
    specification: "",
    brand: "",
    unit: "",
    storageLocation: "",
    safeStock: null,
    remark: ""
  },
  dataList: [],
  typeCodeList: [],
  selectRows: [],
  facCodeList: [], //地块下拉框
  showResults: false,
  foundDevice: ""
});
const { formValue, typeCodeList, dataList, showResults, foundDevice } = toRefs(state);
//获取物资类型下拉列表
const queryTypeCodeList = async () => {
  const data: any = await searchTreeMaterial({
    name: ""
  });
  typeCodeList.value = data;
};
//点击树传typeCode
const nodeClick = (node, data) => {
  formValue.value.typeCode = node.path;
};
//物资类型变化,清除其他输入框
const clearQT = () => {
  formValue.value.name = "";
  formValue.value.specification = "";
  formValue.value.brand = "";
  formValue.value.unit = "";
  formValue.value.safeStock = null;
  formValue.value.remark = "";
};
// 表单校验规则
const rules = computed(() => ({
  typeName: [{ required: true, message: "物资名称不能为空", trigger: ["blur", "change"] }],
  name: [{ required: true, message: "物资名称不能为空", trigger: "blur" }],
  specification: [{ required: true, message: "规格型号不能为空", trigger: "blur" }],
  brand: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
  unit: [{ required: true, message: "单位不能为空", trigger: "blur" }]
}));
//数据回显处理
// 设备附件模糊查询
const attachRemoteMethod = async val => {
  deviceAttachOptions.value = [];
  if (val.toString().length < 1) return;
  searchLoading.value = true;

  const res: any = await queryMaterialTableList({ pageNum: 1, pageSize: 9999, typeCode: formValue.value.typeCode, name: val });
  deviceAttachOptions.value = res?.data || [];
  searchLoading.value = false;
};
const deviceNameAttachChange = async val => {
  // 设备附件新增编辑时候，可以手输入自定义名称，特殊处理
  //查找相同项
  const data: any = await queryMaterialTableList({ typeCode: formValue.value.typeCode, name: val });
  foundDevice.value = data.data.find(item => item.name.toLowerCase() === val.trim().toLowerCase());
  //如果找到相同的,就回显
  if (foundDevice.value) {
    formValue.value.brand = foundDevice.value?.brand;
    formValue.value.specification = foundDevice.value?.specification;
    formValue.value.unit = foundDevice.value?.unit;
    formValue.value.safeStock = foundDevice.value?.safeStock;
    formValue.value.remark = foundDevice.value?.remark;
  } else {
    formValue.value.brand = "";
    formValue.value.specification = "";
    formValue.value.unit = "";
    formValue.value.safeStock = null;
    formValue.value.remark = "";
  }
};
// 打开弹窗
const openDialog = async () => {};
// 关闭弹窗
const closeDialog = () => {
  formValue.value = {};
  emits("closeDialog");
};
// 保存
const handleSubmit = async (formEl: any) => {
  await formEl.validate(async valid => {
    if (valid) {
      if (!foundDevice.value) {
        const params = formValue.value;
        await addToolMaterial(params);
        PxMessage.success("新增成功");
      }
    }
    emits("closeDialog");
    emits("AddTableRow", { ...formValue.value, quantity: 0 });
    closeDialog();
  });
};
</script>

<style lang="scss" scoped>
.equip-dialog {
  .equip-dialog-footer {
    margin-top: 66px;
    text-align: right;
  }
}

:deep(.px-select) {
  width: 100%;
}
</style>
